﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartSpace.OrganizationalStructure
{
    public class OrganizationalStructureDbContext : DbContext
    {
        public OrganizationalStructureDbContext()
            : base("name=" + SmartSpace.Configuration.ConnectionStringName["organization"])
        {
            if (SmartSpace.Configuration.IsAutomaticMigrations)
            {
                Database.SetInitializer<OrganizationalStructureDbContext>(new MigrateDatabaseToLatestVersion<OrganizationalStructureDbContext, AutomaticDbMigrationsConfiguration<OrganizationalStructureDbContext>>());
            }
            else
            {
                Database.SetInitializer<OrganizationalStructureDbContext>(null);
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Organization>().ToTable("__Organization");
            modelBuilder.Entity<Organization>().HasKey(p => p.Id);

            modelBuilder.Entity<OrganizationType>().ToTable("__OrganizationType");
            modelBuilder.Entity<OrganizationType>().HasKey(p => p.Code);

            modelBuilder.Entity<OrganizationTypeRelation>().ToTable("_OrganizationTypeRelation");
            modelBuilder.Entity<OrganizationTypeRelation>().HasKey(p => p.Id);

            base.OnModelCreating(modelBuilder);
        }
    }

    public sealed class AutomaticDbMigrationsConfiguration<TContext> : DbMigrationsConfiguration<TContext> where TContext : System.Data.Entity.DbContext
    {
        public AutomaticDbMigrationsConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }
}
